package com.example.wechathook.util;

import static de.robv.android.xposed.XposedHelpers.callMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import android.content.ContentValues;
import android.database.Cursor;
import android.text.TextUtils;

public class WechatMainDBHelper {

	private Object SQLDB;

	private HashMap<String, String> nicknameCache;

	private HashMap<String, String> mChatroomMemberMap;

	public WechatMainDBHelper(Object dbObject) {
		SQLDB = dbObject;
		nicknameCache = new HashMap<>();
	}

	public Cursor rawQuery(String query) {
		return rawQuery(query, null);
	}

	public Cursor rawQuery(String query, String[] args) {
		return (Cursor) callMethod(SQLDB, "rawQuery", query, args);
	}

	public void insertSQL(String table, String selection, ContentValues contentValues) {
		callMethod(SQLDB, "insert", table, selection, contentValues);
	}

	public void SQLUpdate(String table, ContentValues contentValues, String selection, String[] args) {
		callMethod(SQLDB, "update", table, contentValues, selection, args);
	}

	public Cursor getMessageBySvrId(String msgSrvId) {
		String sql = "select * from message where msgsvrid=?";
		String[] sqlArgs = { msgSrvId };

		return rawQuery(sql, sqlArgs);
	}

	public void insertMessage(String talker, int talkerId, String msg) {
		insertMessage(talker, talkerId, msg, 1, System.currentTimeMillis());
	}

	public void insertSystemMessage(String talker, int talkerId, String msg) {
		insertMessage(talker, talkerId, msg, 10000, System.currentTimeMillis());
	}

	public void insertSystemMessage(String talker, int talkerId, String msg, long createTime) {
		insertMessage(talker, talkerId, msg, 10000, createTime);
	}

	public void insertMessage(String talker, int talkerId, String msg, int type, long createTime) {
		int status = 3;
		long msgSvrId = createTime + (new Random().nextInt());
		long msgId = getNextMsgId();
		ContentValues v = new ContentValues();
		v.put("msgid", msgId);
		v.put("msgSvrid", msgSvrId);
		v.put("type", type);
		v.put("status", status);
		v.put("createTime", createTime);
		v.put("talker", talker);
		v.put("content", msg);
		if (talkerId != -1) {
			v.put("talkerid", talkerId);
		}
		insertSQL("message", "", v);
	}

	public Cursor getLastMsg(String username) {
		String query = "SELECT * FROM message WHERE msgId = (SELECT max(msgId) FROM message WHERE talker='" + username
				+ "')";
		return rawQuery(query);
	}

	public long getNextMsgId() {
		Cursor cursor = rawQuery("SELECT max(msgId) FROM message");
		if (cursor == null || !cursor.moveToFirst())
			return -1;

		long id = cursor.getInt(0) + 1;
		cursor.close();
		return id;
	}

	public String getNickname(String username) {
		if (nicknameCache.containsKey(username)) {
			return nicknameCache.get(username);
		}

		Cursor cursor = getContact(username);
		if (cursor == null || !cursor.moveToFirst())
			return username;

		String name = cursor.getString(cursor.getColumnIndex("conRemark"));
		if (TextUtils.isEmpty(name)) {
			name = cursor.getString(cursor.getColumnIndex("nickname"));
		}
		name = name.trim();
		cursor.close();
		nicknameCache.put(username, name);
		return name;
	}

	private Cursor getContact(String username) {
		String query = "SELECT * FROM rcontact WHERE username = ?";
		return rawQuery(query, new String[] { username });
	}

	public long getContactCnt() {
		String query = "SELECT count(*) FROM contact ";
		Cursor cursor = rawQuery(query, null);
		cursor.moveToFirst();
		return cursor.getLong(0);
	}

	public Set<String> getAllTable() {
		Set<String> tables = new HashSet<String>();
		String query = "SELECT name FROM sqlite_master WHERE type='table' order by name";
		Cursor cursor = rawQuery(query, null);
		while (cursor.moveToNext()) {
			tables.add(cursor.getString(0));
		}
		return tables;
	}

	public List<List<String>> getAllContactWithoutChatRoom() {
		String query = "SELECT * FROM  rcontact WHERE type&1!=0  and type&32=0 and type&8=0 and verifyFlag&8=0 and (username not like '%@%' or (type&1!=0 and type&8=0 and username like '%@talkroom'))";
		Cursor cursor = rawQuery(query, null);
		List<List<String>> data = new ArrayList<List<String>>();

		List<String> cols = new ArrayList<String>();
		int cols_len = cursor.getColumnCount();
		for (int i = 0; i < cols_len; i++) {
			cols.add(cursor.getColumnName(i));
		}
		data.add(cols);

		while (cursor.moveToNext()) {
			List<String> row = new ArrayList<String>();
			for (int j = 0; j < cols_len; j++) {
				int type = cursor.getType(j);
				switch (type) {
				case 1:// int
					row.add(cursor.getInt(j) + "");
					break;
				case 2:// float
					row.add(cursor.getFloat(j) + "");
					break;
				case 4:// blob
					row.add("blob数据");
					break;
				default:
					row.add(cursor.getString(j));
					break;
				}
			}
			data.add(row);
		}
		return data;
	}

	private String getChatroomName(String username) {
		String name = getNickname(username);
		if (!TextUtils.isEmpty(name))
			return name;

		String query = "SELECT * FROM chatroom WHERE chatroomname = ?";
		Cursor cursor = rawQuery(query, new String[] { username });
		if (cursor == null || !cursor.moveToFirst())
			return null;

		name = cursor.getString(cursor.getColumnIndex("displayname"));
		cursor.close();
		return name;
	}

	public HashMap<String, String> getChatRoomMembers() {
		String query = "SELECT * FROM chatroom";
		Cursor cursor = rawQuery(query);

		HashMap<String, String> map = new HashMap<>();

		if (cursor == null || !cursor.moveToFirst())
			return map;

		do {
			String memberlist = cursor.getString(cursor.getColumnIndex("memberlist"));
			String displayname = cursor.getString(cursor.getColumnIndex("displayname"));

			String[] members = memberlist.split(";");
			String[] names;
			if (displayname.contains("、")) {
				names = displayname.split("、");
			} else {
				names = displayname.split(",");
			}

			for (int i = 0; i < members.length; i++) {
				map.put(members[i].trim(), names[i].trim());
			}

		} while (cursor.moveToNext());
		cursor.close();

		return map;
	}

	public String getChatroomMemberName(String username) {
		if (mChatroomMemberMap == null) {
			mChatroomMemberMap = getChatRoomMembers();
		}

		if (mChatroomMemberMap.containsKey(username)) {
			return mChatroomMemberMap.get(username);
		}

		// reload
		mChatroomMemberMap = getChatRoomMembers();
		if (mChatroomMemberMap.containsKey(username)) {
			return mChatroomMemberMap.get(username);
		}
		return null;
	}

}
